package com.hdl.servlet.user;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdl.entity.HdlUser;
import com.hdl.util.CookieUtil;

/**
 * ajax用户退出
 * @author Administrator
 *
 */
@WebServlet("/logout.let")
public class LogoutServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//从session中删除数据
		HttpSession session = req.getSession();
		session.removeAttribute("user");
		session.removeAttribute("cart");
		
		//删除自动登录的cookie
		Cookie cookie = CookieUtil.getCookie(req.getCookies(), "auto_login");
		if(cookie != null) {
			System.out.println(cookie.getName()+":"+cookie.getValue());
			cookie.setMaxAge(0);//删除cookie
			resp.addCookie(cookie);
		}
		
		//创建核心对象
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String,Object> map = new HashMap<String, Object>();
		
		//判断是否删除成功
		HdlUser user = (HdlUser) session.getAttribute("user");
		if(user != null) {//删除失败
			map.put("code", 1);
		}else {//成功
			map.put("code", 2);
		}
		
		//写回消息
		mapper.writeValue(resp.getOutputStream(), map);
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
